<template>
  <div class="organizationManagement h100">
    <div class="PageContent">
      <el-col :span="4" class="left-tree">
        <el-tree
          :data="treeData"
          ref="organizationtree"
          :props="defaultProps"
          node-key="id"
          default-expand-all
          check-strictly
          highlight-current
          @node-click="handleClick"
        ></el-tree>
      </el-col>
      <el-col :span="20" class="right-tree">
        <el-row style="text-align: left;line-height: 5em;">
          <el-button type="primary" v-if="btnRight.btnOrgManRefresh" @click="refresh()">刷新</el-button>
          <el-button type="primary" v-if="btnRight.btnOrgManAdd" @click="add()">关联兼职</el-button>
          <el-button type="danger" v-if="btnRight.btnOrgManDelete" @click="remove()">取消兼职</el-button>
        </el-row>
        <el-table
          ref="organizationTable"
          :data="tableData"
          :header-cell-style="{background:'rgb(222,225,230)',color:'#606266'}"
          border
          @row-click="handleRowClick"
          @select="select"
          @select-all="selectAll"
          style="width: 100%;height: calc(100% - 80px);overflow-y: scroll"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column property="fullName" label="员工姓名" align="center" width="200"></el-table-column>
          <el-table-column property="jobNo" label="员工编号" align="center" width="200"></el-table-column>

          <el-table-column property="sort" align="center" label="是否兼职" width="200">
            <template v-slot="{row}">
              <p v-if="row.partCode==0">
                <span>否</span>
              </p>
              <p v-else-if="row.partCode==1">
                <span>是</span>
              </p>
              <p v-else-if="row.partCode==null">
                <span>否</span>
              </p>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </div>
    <el-dialog
      title="兼职人员添加"
      :visible.sync="dialogVisible"
      width="700px"
      v-dialogDrag
      border
      @close="close"
    >
      <el-row>
        <el-col :span="8">
          <el-tree
            :data="treeDatas"
            ref="organizationtrees"
            :props="defaultProps"
            node-key="id"
            default-expand-all
            check-strictly
            :highlight-current="false"
            @node-click="handleClicks"
          ></el-tree>
        </el-col>
        <el-col :span="12">
          <el-form
            :model="saveData.organization"
            :rules="rules"
            class="saveform"
            ref="organizationdialog"
            :inline="true"
            label-width="100px"
            :disabled="saveFlag"
          >
            <el-row>
              <el-form-item>
                <el-checkbox-group v-model="saveData.PartTimeEmployees" style="width:100px">
                  <el-checkbox
                    v-for=" item in EmployeeList"
                    :key="item.userId"
                    :label="item.userId"
                  >{{item.fullName}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button
          type="primary"
          v-if="btnRight.btnOrgManSave"
          @click="save()"
          :disabled="saveFlag"
        >保存</el-button>
        <el-button v-if="btnRight.btnOrgManCancel" @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API from "@/api/stystemManagement";
export default {
  name: "partTimeManagement",
  data() {
    return {
      EmployeeList: [], //员工列表

      rules: {},
      treeData: [
        {
          id: 0,
          label: "组织机构",
          children: [],
        },
      ],
      treeDatas: [
        {
          id: 0,
          label: "组织机构",
          children: [],
        },
      ],
      defaultProps: {
        children: "children",
        label: "label",
      },
      tableData: [],

      tableSelection: [],
      dialogVisible: false, //对话框
      saveFlag: false, //保存标志
      onpresscTime: 0, //  阻止短时间内连续点击
      saveData: {
        PartTimeEmployees: [],
        organization: {
          id: 0,
          parentId: 0,
          parentName: "string",
          organizationCode: "string",
          organizationName: "string",
          organizationDescribe: "string",
          organizationTypeCode: 0,
          address: "string",
          disableState: 0,
          remark: "string",
          sort: 0,
          version: 0,
        },
      }, //对话框需要数据
      btnRight: {
        btnOrgManAdd: true, //添加
        btnOrgManEdit: true, //修改
        btnOrgManDelete: true, //删除
        btnOrgManSave: true, //保存
        btnOrgManCancel: true, //取消
        btnOrgManRefresh: true, //刷新
      },
    };
  },
  mounted() {
    this.loadOrganizationTreeWithParentIdData(0);
    //载入按钮
    this.btnRight = this.$route.meta.buttons;
    //遍历属性赋值将true与false字符串转换成布尔型的值
    for (let key of Object.keys(this.btnRight)) {
      this.btnRight[key] =
        this.btnRight[key] || this.btnRight[key] == "true" ? true : false;
    }
  },
  methods: {
    //tree单选
    handleClick(data, checked, node) {
      console.log(data, checked, node);
      if (checked && data.label != "组织机构") {
        this.$refs.organizationtree.setCheckedNodes([data]);
        //获取列表数据
        this.loadOrganizationListWithParentIdData(data.id);
      }
    },
    handleClicks(data, checked, node) {
      // if (this.$refs.organizationtree.getCheckedNodes()[0].id === data.id) {
      //   this.$message("当前员工已在该部门就职");
      //   return;
      // }
      if (checked && data.label != "组织机构") {
        this.$refs.organizationtrees.setCheckedNodes([data]);
      }
    },
    //点击行触发，选中或不选中复选框
    handleRowClick(row, column, event) {
      if (this.tableSelection.length > 0) {
        this.$refs.organizationTable.toggleRowSelection(
          this.tableSelection[0],
          false
        );
      }
      this.$refs.organizationTable.toggleRowSelection(row);
      this.tableSelection = [row];
    }, //选择
    select(selection, row) {
      console.log(selection, row);
      // 选择项大于1时
      if (selection.length > 1) {
        let del_row = selection.shift();
        // console.log('把数组的第一个元素从其中删除后', selection);
        this.$refs.organizationTable.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
      }
      this.tableSelection = selection;
    },

    selectAll(selection) {
      if (selection.length > 1) {
        selection.length = 1;
      }
      this.tableSelection = selection;
    },
    /**********************方法**********************/
    //刷新
    refresh() {
      let data = this.$refs.organizationtree.getCheckedNodes();
      if (data.length) {
        this.loadOrganizationListWithParentIdData(data[0].id);
      }
    },
    //table中类型添加
    add() {
      let dataSelection = this.$refs.organizationtree.getCheckedNodes();
      if (dataSelection.length == 0) {
        this.$message("未选中");
        return;
      } else {
        this.saveData.organization = {
          id: 0,
          parentId: dataSelection[0].id,
          parentName: dataSelection[0].label,
        };
        console.log(this.saveData.organization);

        let index = this.treeDatas[0].children.findIndex(
          (item) => item.id === dataSelection[0].id
        );
        this.treeDatas[0].children.splice(index, 1);

        // console.log(index)
      }
      this.dialogVisible = true;
    },
    //table中类型修改

    //table中服务物品类型删除
    remove() {
      let data = this.tableSelection;
      let dataSelection = this.$refs.organizationtree.getCheckedNodes();
      console.log(dataSelection);
      
      if (data.length == 0) {
        this.$message("未选中");
        return;
      }
      this.$confirm("删除信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let postData = {
            id: data[0].id,
            version: data[0].version,
          };

          API["EmployeePartTimeJobDeletion"](postData)
            .then((response) => {
              const { message } = response;
              this.$message(message);
              this.tableSelection = [];
              if (dataSelection[0].id == 0) {
                //添加一级菜单parentId为0
                this.loadOrganizationTreeWithParentIdData();
                //添加二级菜单parentId为非0
                this.loadOrganizationListWithParentIdData(0);
              } else {
                //添加二级菜单parentId为非0
                this.loadOrganizationListWithParentIdData(dataSelection[0].id);
              }
              this.dialogVisible = false;
            })
            .catch((error) => {
              this.$message(error);
            });
        })
        .catch(() => {
          //几点取消的提示
        });
    },
    //加载树
    loadOrganizationTreeWithParentIdData() {
      let postData = {
        id: 0,
      };
      API["StaffTreeStructure"](postData)
        .then((response) => {
          const { data } = response;
          this.treeData[0].children = data;
          this.treeDatas[0].children = JSON.parse(JSON.stringify(data));
        })
        .catch((error) => {
          this.$message(error);
        });
    },
    //加载列表
    loadOrganizationListWithParentIdData(id) {
      let postData = {
        companyId: id,
      };
      API["EmployeeList"](postData)
        .then((response) => {
          const { data } = response;
          if (!data) {
            this.$message("数据读取失败");
            return;
          }

          this.tableData = data;
          this.EmployeeList = data;
        })
        .catch((error) => {
          this.$message(error);
        });
    },
    // 弹框关闭回调
    close() {
      this.$refs.organizationtrees.setCheckedNodes([]);
      //删除组织机构id
      this.saveData.PartTimeEmployees = [];
      this.treeDatas[0].children = JSON.parse(
        JSON.stringify(this.treeData[0].children)
      );
      //删除员工id
    
    
    },

    //保存信息
    save() {
      if (!this.$refs.organizationtrees.getCheckedNodes().length) {
        this.$message("请选择组织机构");
        return;
      }

      if (Date.now() - this.onpresscTime > 2000) {
        this.onpresscTime = Date.now();
        console.log(Date.now());
      } else {
        return;
      }

      this.$refs.organizationdialog.validate((valid) => {
        if (valid) {
          this.saveFlag = true;
          let postData = this.saveData.organization;
          API["PartTimeEmployeePreservation"]({
            businessSystemId: "2",
            id: 0,
            departmentId: 0,
            companyId: this.$refs.organizationtrees.getCheckedNodes()[0].id,
            userIds: this.saveData.PartTimeEmployees,
          })
            .then((response) => {
              const { message } = response;
              this.$message(message);
              if (postData.parentId == 0) {
                //添加一级菜单parentId为0
                this.loadOrganizationTreeWithParentIdData();
              }
              //添加二级菜单parentId为非0

              this.loadOrganizationListWithParentIdData(
                this.saveData.organization.parentId
              );
              this.dialogVisible = false;
              this.tableSelection = [];
              this.saveFlag = false;

              // this.$refs.organizationtrees.setCheckedNodes([]);
              // //删除组织机构id
              this.saveData.PartTimeEmployees = [];
            })
            .catch((error) => {
              this.$message(error);
              this.saveFlag = false;
            });
        }
      });
    }, //验证整数
    onlySortNumber() {
      // 先把非数字的都替换掉，除了数字和.
      let obj = this.saveData.organization.sort;
      obj = Number.parseInt(obj);
      this.saveData.organization.sort = obj;
    },
    /**********************方法**************************/
  },
  watch: {
    dialogVisible() {
      if (this.dialogVisible == false) {
        this.$nextTick(() => {
          this.$refs.organizationdialog.resetFields();
        });
      }
    },
  },
};
</script>

<style scoped>
.vehicleManagement {
  height: 100vh;
  background-color: red;
}
.content {
  width: 500px;
  display: inline-block;
}
.ruleItem {
  width: 532px;
  max-height: 6em;
  overflow-y: auto;
  line-height: 1.5em;
}
.ruleItem .content {
  width: 100%;
  padding-top: 10px;
}
</style>

